import os
import subprocess

class GPUVideoConverter:
    '''
    批量将视频文件转换为 MP4 格式，并使用 NVIDIA GPU
    '''
    def __init__(self, input_folder, output_folder):
        self.input_folder = input_folder
        self.output_folder = output_folder
        os.makedirs(self.output_folder, exist_ok=True)
        self.supported_exts = ('.mp4', '.mkv', '.avi', '.mov', '.flv', '.ts', '.webm')

    def convert_file(self, input_path):
        """使用 NVIDIA GPU 硬件编码器 h264_nvenc 转换单个文件为 MP4"""
        filename_wo_ext = os.path.splitext(os.path.basename(input_path))[0]
        output_path = os.path.join(self.output_folder, f"{filename_wo_ext}.mp4")

        try:
            subprocess.run([
                'ffmpeg', '-y',
                '-hwaccel', 'cuda',           # CUDA 硬件加速解码
                '-i', input_path,
                '-c:v', 'h264_nvenc',         # GPU 加速编码
                '-preset', 'fast',            # 编码速度 preset
                '-c:a', 'aac', '-b:a', '192k',# 音频
                output_path
            ], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
            print(f"✅ 已转换: {input_path} -> {output_path}")
        except subprocess.CalledProcessError:
            print(f"❌ 转换失败: {input_path}")

    def convert_all(self):
        """批量转换输入文件夹内所有视频"""
        for filename in os.listdir(self.input_folder):
            if filename.lower().endswith(self.supported_exts):
                input_path = os.path.join(self.input_folder, filename)
                self.convert_file(input_path)

if __name__ == "__main__":
    input_folder = input("📂 输入视频文件夹路径: ").strip('"')
    output_folder = input("📂 输出文件夹路径: ").strip('"')

    if not os.path.isdir(input_folder):
        print("❌ 输入文件夹不存在")
    else:
        converter = GPUVideoConverter(input_folder, output_folder)
        converter.convert_all()
        print("🎉 全部转换完成！")
